<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/27
 * Time: 9:58
 */

namespace Fanpaiji;

use OSS\Core\OssException;
use OSS\OssClient;

class AliyunUpdate
{
    use FileFunc;

    private $OSS_ACCESS_ID = 'LTAIPgq6PUEgaMk3';
    private $OSS_ACCESS_KEY = 'H9w5KTkPzRXDtydayorG9yLFjGee0v';
    private $OSS_ENDPOINT = 'http://oss-cn-shenzhen.aliyuncs.com';
    private $OSS_TEST_BUCKET = 'ryp';

    private $ossClient;

    private $_http = 'http://p.ecpei.cn/';
    public function __construct()
    {
        /**
         * 根据Config配置，得到一个OssClient实例
         * @return OssClient 一个OssClient实例
         */
        try {
            $this->ossClient = new OssClient($this->OSS_ACCESS_ID, $this->OSS_ACCESS_KEY, $this->OSS_ENDPOINT, false);
        } catch (OssException $e) {
            $this->writeFile( __DIR__.'/error/OSS' , 'error_'.date("Y-m-d"), $e->getMessage());
            return ['status' => 1, 'messages' => $e->getMessage(), 'data' => []];
        }
    }


    public function getBucketName()
    {
        return $this->OSS_TEST_BUCKET;
    }


    public function updateFile( $download_file = '', $object = '' )
    {
        try {
            if ( !$download_file || !is_file( $download_file ) ) throw new \Exception( "文件路径错误" );
            $bucketName = $this->getBucketName();
            $object = $object ? $object : "goods_brand/" . time().'jpg' ;
            if (is_null($this->ossClient)) throw new \Exception( "连接失败" );
            //*******************************简单使用***************************************************************
            // 先把本地的example.jpg上传到指定$bucket, 命名为$object
            $data = $this->ossClient->uploadFile( $bucketName , $object , $download_file );
        } catch ( \Exception $exception ) {
            $this->writeFile( '/error/OSS' , 'error_'.date("Y-m-d"), $exception->getMessage(), 'a+');
            $this->updateFile( $download_file, $object );
            echo $exception->getMessage();
//            return ['status' => 1, 'messages' => $exception->getMessage(), 'data' => []];
        }
        return ['status' => 0, 'messages' => 'success', 'data' => ['url' => $this->_http.$object]];;
    }



    public function updateFile2222( $download_file = '', $object = '' )
    {
        $returnData = ['返回结果'];
        try {
            $data = ['url' => '23'];
            if ( $object < 10 ) {
                echo $object;
                $data = [];
                throw new \Exception( "error abc " );
            }

        } catch ( \Exception $exception ) {
            self::updateFile2222( $download_file, 20 );
            $this->writeFile( '/error/OSS' , 'error_'.date("Y-m-d"), $exception->getMessage(), 'a+');
            echo $exception->getMessage();
        }


            $returnData = ['status' => 0, 'messages' => 'success', 'data' => ['url' => $object]];
            return $returnData;

    }
}